<?php 
function to_mysql_date($time) {
  return date('Y-m-d H:i:s', $time);
}

function gen_sep_str($elements, $sep=',', $drop_null_str = true) {
  $str = "";
  foreach($elements as $element) {
    $str .= ($element != "" || !drop_null_str) ? $element.$sep : "";
  }
  return $str != "" ? substr($str, 0, -strlen($sep)) : "";
}

function db_insert($table_name, $fields) {
  $n = count($fields);
  $ret = 0;
  if($n > 0) {
    $field_list = gen_sep_str(array_keys($fields));
    $value_list = gen_sep_str(array_values($fields));
    $sql = "insert into $table_name ($field_list) values($value_list)";
    // echo "sql : ".$sql;
    if(mysql_query($sql)) {
      $ret = mysql_insert_id();
    }
  }
  return $ret;
}

function db_update($table_name, $update_fields, $id_value, 
      $id_field_name = 'id') {
  $where = " where $id_field_name= '$id_value'";
  $elements = array();
  while(list($field, $value) = each($update_fields)) {
    array_push($elements, "$field = $value");
  }
  $sql = "update $table_name set ".gen_sep_str($elements).$where;
  //echo 'sql: '.$sql;
  mysql_query($sql);
}

function db_get($sql) {
  //echo 'sql: '.$sql;
  $query = mysql_query($sql);
  $rows = array();
  while($row = mysql_fetch_array($query)) {
    array_push($rows, $row);
  }
  return $rows;
}

function db_get_one_col($sql) {
  $values = array();
  $rows = db_get($sql);
  
  foreach($rows as $row) {
    array_push($values, $row[0]);
  }
  
  return $values;
}

function db_get_one_value($sql) {
  $values = db_get_one_col($sql);
  return 1==count($values) ? $values[0] : 0;
}

function db_delete($table_name, $id_value, $id_field_name = 'id') {
  $sql = "delete from $table_name where $id_field_name = '$id_value'";
  mysql_query($sql);
}

function get_project_name_by_id($project_id) {
  $sql = "select project_name from project_info where id = $project_id";
  $rows = db_get($sql);
  
  if(count($rows) > 0) {
    return $rows[0]['project_name'];
  }  else {
    return "";
  }
}

function is_administrator($user_id) {
  $sql = "select is_administrator from user_info where id = $user_id";
  // echo 'sql = '.$sql;
  return db_get_one_value($sql) != 0;
}

function is_manager($user_id) {
  $sql = "select is_manager from user_info where id = $user_id";
  return db_get_one_value($sql)!=0;
}

function is_senior_manager($user_id) {
  $sql = "select is_senior_manager from user_info where id = $user_id";
  return db_get_one_value($sql)!=0;
}


?>

